<template>
    <div class="countdown-box">
        <a class="code-btn" :class="{ 'disabled': disabled }" @click="!disabled ? getCode() : ''"
            v-text="countdownConfig.btnText"></a>
    </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, onUnmounted } from 'vue'

const defaultTime = ref('')

const disabled = ref(false)

const props = defineProps({
    countdownConfig: Object
})

const emit = defineEmits()

function getCode() {
    defaultTime.value = props.countdownConfig.time
    countDown()
}

// 倒计时
function countDown(){
    if (disabled.value) {
        return false
    }

    // 倒计时开始后按钮置灰
    disabled.value = true

    let timer = setInterval(() => {
        props.countdownConfig.btnText = `${props.countdownConfig.time}s可重发`
        props.countdownConfig.time--
        if (props.countdownConfig.time < 0) {
            disabled.value = false
            props.countdownConfig.btnText = props.countdownConfig.resetText
            props.countdownConfig.time = defaultTime
            clearInterval(timer)
            emit('end')
        }
    }, 1000)
    return
}
// export default {

//     destroyed() {
//         clearInterval(timer)
//     }
// }
</script>

<style lang="less" scoped>
.countdown-box {
    display: inline-block;
    height: 38px;
    line-height: 38px;
    border-radius: 4px;
    overflow: hidden;
}

.countdown-box .code-btn {
    height: inherit;
    display: inline-flex;
    align-items: center;
    padding: 0 15px;
    color: #fff;
    font-size: 14px;
    border-radius: 4px;
    background-color: #EF1F1F;
    cursor: pointer;
}

.countdown-box .disabled {
    opacity: .5;
    cursor: no-drop;
}</style>